package com.ruoyi.discuss.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ObjectUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.discuss.domain.SysDiscuss;
import com.ruoyi.discuss.domain.SysDiscussLike;
import com.ruoyi.discuss.mapper.SysDiscussLikeMapper;
import com.ruoyi.discuss.mapper.SysDiscussMapper;
import com.ruoyi.discuss.service.IDiscussService;
import com.ruoyi.discuss.vo.DiscussVO;
import com.ruoyi.discuss.vo.ReplyVO;
import com.ruoyi.discuss.vo.SecondReplyVO;
import com.ruoyi.discuss.vo.TreeDiscussVO;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class DiscussServiceImpl implements IDiscussService {

    @Autowired
    private SysDiscussMapper discussMapper;
    @Autowired
    private SysDiscussLikeMapper discussLikeMapper;
    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public List<DiscussVO> listDiscuss(DiscussVO discussVO) {
        List<DiscussVO> discussVOS = discussMapper.listDiscuss(discussVO);
        if (CollectionUtils.isEmpty(discussVOS)) {
            return discussVOS;
        }
        //查询用户的点赞数
        Map<Long,Long> likeMap = new HashMap<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysDiscussLike> likeList = discussLikeMapper.selectListByUserId(loginUser.getUserId());
        if (likeList != null && likeList.size() > 0) {
            likeList.forEach(item -> {
                likeMap.put(item.getDiscussId(),item.getLikeId());
            });
        }
        //
        List<Long> discussIds = new ArrayList<>();
        discussVOS.forEach(item -> {
            discussIds.add(item.getDiscussId());
            if (StringUtils.isEmpty(item.getAvatar())) {
                item.setAvatar("/static/img/profile.473f5971.jpg");
            }
            if (likeMap.get(item.getDiscussId()) != null) {
                item.setLike(true);
            } else {
                item.setLike(false);
            }
        });
        //
        List<Long> userIds = new ArrayList<>();
        Map<Long,List<SysDiscuss>> orgReplyMap = new HashMap<>();
        Map<Long,List<SysDiscuss>> orgSecondReplyMap = new HashMap<>();
        //获取回复
        List<SysDiscuss> orgReplys = discussMapper.listReply(discussIds);
        if (!CollectionUtils.isEmpty(orgReplys)) {
            List<Long> replyIds = new ArrayList<>();
            orgReplys.forEach(item -> {
                replyIds.add(item.getDiscussId());
                if (item.getPubUserId() != null && item.getPubUserId() > 0) {
                    userIds.add(item.getPubUserId());
                }
                if (item.getReplyUserId() != null && item.getReplyUserId() > 0) {
                    userIds.add(item.getPubUserId());
                }
                List<SysDiscuss> tmpList = orgReplyMap.get(item.getParentDiscussId());
                if (CollectionUtils.isEmpty(tmpList)) {
                    tmpList = new ArrayList<>();
                    tmpList.add(item);
                    orgReplyMap.put(item.getParentDiscussId(),tmpList);
                } else {
                    tmpList.add(item);
                }
            });
            //获取二次回复
            List<SysDiscuss> orgSecondReplys = discussMapper.listReply(replyIds);
            if (!CollectionUtils.isEmpty(orgSecondReplys)) {
                orgSecondReplys.forEach(item -> {
                    if (item.getPubUserId() != null && item.getPubUserId() > 0) {
                        userIds.add(item.getPubUserId());
                    }
                    if (item.getReplyUserId() != null && item.getReplyUserId() > 0) {
                        userIds.add(item.getPubUserId());
                    }
                    List<SysDiscuss> tmpList = orgSecondReplyMap.get(item.getParentDiscussId());
                    if (CollectionUtils.isEmpty(tmpList)) {
                        tmpList = new ArrayList<>();
                        tmpList.add(item);
                        orgSecondReplyMap.put(item.getParentDiscussId(),tmpList);
                    } else {
                        tmpList.add(item);
                    }
                });
            }
        }
        //获取用户
        Map<Long, SysUser> userMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userIds)) {
            List<SysUser> users = sysUserMapper.listUsersByUserIds(userIds);
            if (!CollectionUtils.isEmpty(users)) {
                users.forEach(item -> {
                    userMap.put(item.getUserId(),item);
                });
            }
        }
        //组装
        discussVOS.forEach(item -> {
            if (StringUtils.isEmpty(item.getAvatar())) {
                item.setAvatar("/static/img/profile.473f5971.jpg");
            }
            List<SysDiscuss> tmpReplys = orgReplyMap.get(item.getDiscussId());
            if (!CollectionUtils.isEmpty(tmpReplys)) {
                List<ReplyVO> replyVOS = new ArrayList<>();
                tmpReplys.forEach(it -> {
                    SysUser pubUser = userMap.get(it.getPubUserId());
                    ReplyVO replyVO = new ReplyVO();
                    replyVO.setAvatar(pubUser == null ? "" : pubUser.getAvatar());
                    replyVO.setContent(it.getContent());
                    replyVO.setCourseNo(it.getCourseNo());
                    replyVO.setCreateTime(it.getCreateTime());
                    replyVO.setLikeCount(it.getLikeCount());
                    replyVO.setDiscussCount(it.getDiscussCount());
                    replyVO.setNickName(pubUser == null ? "" : pubUser.getNickName());
                    replyVO.setParentDiscussId(item.getDiscussId());
                    replyVO.setReplyId(it.getDiscussId());
                    replyVO.setUserId(it.getPubUserId());
                    replyVO.setUserName(pubUser == null ? "" : pubUser.getUserName());
                    if (StringUtils.isEmpty(replyVO.getAvatar())) {
                        replyVO.setAvatar("/static/img/profile.473f5971.jpg");
                    }
                    if (likeMap.get(it.getDiscussId()) != null) {
                        replyVO.setLike(true);
                    } else {
                        replyVO.setLike(false);
                    }
                    //
                    List<SysDiscuss> tmpSecondReplys = orgSecondReplyMap.get(it.getDiscussId());
                    if (!CollectionUtils.isEmpty(tmpSecondReplys)) {
                        List<SecondReplyVO> secondReplyVOS = new ArrayList<>();
                        tmpSecondReplys.forEach(tt -> {
                            SysUser sPubUser = userMap.get(tt.getPubUserId());
                            SecondReplyVO secondReplyVO = new SecondReplyVO();
                            secondReplyVO.setAvatar(sPubUser == null ? "" : sPubUser.getAvatar());
                            secondReplyVO.setContent(tt.getContent());
                            secondReplyVO.setCourseNo(tt.getCourseNo());
                            secondReplyVO.setCreateTime(tt.getCreateTime());
                            secondReplyVO.setNickName(sPubUser == null ? "" : sPubUser.getNickName());
                            secondReplyVO.setUserName(sPubUser == null ? "" : sPubUser.getUserName());
                            secondReplyVO.setParentReplyId(it.getDiscussId());
                            SysUser sReUser = userMap.get(tt.getReplyUserId());
                            secondReplyVO.setReplyNickName(sReUser == null ? "" : sReUser.getNickName());
                            secondReplyVO.setReplyUserId(tt.getReplyUserId());
                            secondReplyVO.setReplyUserName(sReUser == null ? "" : sReUser.getUserName());
                            secondReplyVO.setUserId(tt.getPubUserId());
                            if (StringUtils.isEmpty(secondReplyVO.getAvatar())) {
                                secondReplyVO.setAvatar("/static/img/profile.473f5971.jpg");
                            }
                            secondReplyVOS.add(secondReplyVO);
                        });
                        //
                        Collections.sort(secondReplyVOS, new Comparator<SecondReplyVO>() {
                            @Override
                            public int compare(SecondReplyVO o1, SecondReplyVO o2) {
                                return (int)(o1.getCreateTime().getTime() - o2.getCreateTime().getTime());
                            }
                        });
                        replyVO.setSecondReplys(secondReplyVOS);
                    } else {
                        replyVO.setSecondReplys(new ArrayList<>());
                    }
                    //
                    replyVOS.add(replyVO);
                });
                //
                Collections.sort(replyVOS, new Comparator<ReplyVO>() {
                    @Override
                    public int compare(ReplyVO o1, ReplyVO o2) {
                        return (int)(o1.getCreateTime().getTime() - o2.getCreateTime().getTime());
                    }
                });
                item.setReplys(replyVOS);
            } else {
                item.setReplys(new ArrayList<>());
            }
        });

        return discussVOS;
    }

    @Override
    public List<TreeDiscussVO> listSysDiscuss(TreeDiscussVO treeDiscussVO) {
        return discussMapper.listSysDiscuss(treeDiscussVO);
    }

    @Override
    public List<TreeDiscussVO> listSysReply(Long parentDiscussId) {
        return discussMapper.listSysReply(parentDiscussId);
    }

    @Override
    @Transactional
    public SysDiscuss updateLikeCount(Long discussId,Long userId) {
        ObjectUtil.checkNull(discussId,"评论ID为空");
        ObjectUtil.checkNull(userId,"用户ID为空");
        SysDiscussLike discussLike = discussLikeMapper.selectOneByDiscussId(discussId,userId);
        if (discussLike == null) {
            discussLike = new SysDiscussLike();
            discussLike.setCreateTime(new Date());
            discussLike.setDiscussId(discussId);
            discussLike.setUpdateTime(discussLike.getCreateTime());
            discussLike.setUserId(userId);
            discussLikeMapper.insertSysDiscussLike(discussLike);
            discussMapper.updateIncLikeCount(discussId);
        } else {
            discussMapper.updateDecLikeCount(discussId);
            discussLikeMapper.deleteByLikeId(discussLike.getLikeId());
        }
        return discussMapper.getOneByDiscussId(discussId);
    }

    @Override
    @Transactional
    public void insertDiscuss(DiscussVO discussVO) {
        SysDiscuss discuss = new SysDiscuss();
        discuss.setContent(discussVO.getContent());
        discuss.setCourseNo(discussVO.getCourseNo());
        discuss.setCreateTime(new Date());
        discuss.setDelFlag(0);
        discuss.setDiscussCount(0);
        discuss.setLikeCount(0);
        discuss.setParentDiscussId(0L);
        discuss.setPubUserId(discussVO.getUserId());
        discuss.setReplyUserId(0L);
        discuss.setUpdateTime(discuss.getCreateTime());
        discussMapper.insertSysDiscuss(discuss);
    }

    @Override
    @Transactional
    public void reply(ReplyVO replyVO) {
        SysDiscuss parentDiscuss = discussMapper.getOneByDiscussId(replyVO.getParentDiscussId());
        ObjectUtil.checkNull(parentDiscuss,"父评论不存在");
        SysDiscuss discuss = new SysDiscuss();
        discuss.setContent(replyVO.getContent());
        discuss.setCourseNo(parentDiscuss.getCourseNo());
        discuss.setCreateTime(new Date());
        discuss.setDelFlag(0);
        discuss.setDiscussCount(0);
        discuss.setLikeCount(0);
        discuss.setParentDiscussId(parentDiscuss.getDiscussId()); //要回复的评论
        discuss.setPubUserId(replyVO.getUserId());
        discuss.setReplyUserId(0L);
        discuss.setUpdateTime(discuss.getCreateTime());
        discussMapper.insertSysDiscuss(discuss);
        discussMapper.updateIncDiscussCount(parentDiscuss.getDiscussId());
    }

    @Override
    @Transactional
    public void secondReply(SecondReplyVO secondReplyVO) {
        SysDiscuss parentReply = discussMapper.getOneByDiscussId(secondReplyVO.getParentReplyId());
        ObjectUtil.checkNull(parentReply,"父回复不存在");
        SysDiscuss discuss = new SysDiscuss();
        discuss.setContent(secondReplyVO.getContent());
        discuss.setCourseNo(parentReply.getCourseNo());
        discuss.setCreateTime(new Date());
        discuss.setDelFlag(0);
        discuss.setDiscussCount(0);
        discuss.setLikeCount(0);
        discuss.setParentDiscussId(parentReply.getDiscussId()); //要回复的评论
        discuss.setPubUserId(secondReplyVO.getUserId());
        discuss.setReplyUserId(secondReplyVO.getReplyUserId());
        discuss.setUpdateTime(discuss.getCreateTime());
        discussMapper.insertSysDiscuss(discuss);
        discussMapper.updateIncDiscussCount(parentReply.getDiscussId());
    }

    @Override
    @Transactional
    public void delDiscuss(Long discussId) {
        SysDiscuss discuss = discussMapper.getOneByDiscussId(discussId);
        ObjectUtil.checkNull(discuss,"评论或回复不存在");
        discussMapper.delDiscuss(discussId);
        discussMapper.updateDecDiscussCount(discuss.getParentDiscussId());
    }
}
